<template>
	<div class="content goods_detail">
		<v-header :hasTitle="true" title="商品详情" :hasBack="true" :goBack="goBack">
		</v-header>
		<div class="midPart" ref="midPart">
			<div :style="{height: midPartHeight}" style="width:'100%'">
				<VerticalScroll ref="verticalScroll">
					<div>
						<div id="shade" ref="shade"></div>
						<v-carousel :swipimgage="transferUrl" :swipimgagewidth="screenWidth" :swipimgageheight="screenWidth"></v-carousel>
						<div style="width:100%;display:flex;">
							<h2 class="aui-ellipsis-2 goodsname" style="font-weight:bold;text-align:left;float:left;flex:1;background: white;">
          {{goodsName}}
          <span style="display:inline-block;margin-left:5px;"></span>
        </h2>
							<div style="display:flex;width:3.6rem;align-items:center;justify-content:space-between;" @click="goSource" v-if="traceabilityaddress">
								<i class="icon njfont nj-suyuan"></i>
								<p style="padding: 0 .75rem 0 0;">溯源</p>
							</div>
						</div>
						<p class="goodssubname" v-if="secTitle" style="text-align:left;font-size:.75rem;">
							{{secTitle}}
						</p>
						<p class="price">
							<span class="prices_text" style="text-align:left;display:inline-block;min-width:3.2rem;" v-if="goodsType == 6">
          ¥<em class="wsprice">{{perPrice}}</em>
          <del class="normalprice" v-if="normalDisplay"
               style="display:inline-block;background:#EFEFEE;color:#9A9A9A;font-size:.75rem;height:1rem;">
            ￥{{normalprice}}
          </del>
        </span>
							<span v-if="goodsType == 6">/500g</span>
							<span class="prices_text" style="text-align:left;display:inline-block;min-width:3.2rem;" v-if="goodsType != 6">
          ¥<em class="wsprice">{{wsprice}}</em>
          <del class="normalprice" v-if="normalDisplay"
               style="display:inline-block;background:#EFEFEE;color:#9A9A9A;font-size:.75rem;height:1rem;">￥{{normalprice}}</del>
        </span>
							<span v-if="goodsType != 6 && goodsType != 7">/{{minsaleqty}}{{goodsunit}}</span>
							<span v-if="goodsType == 7">/{{minsaleqty}}g</span>
							<span class="intgoodsnumdiv">{{goodsnum * requiredIntegral}}</span> 积分
							<span style="float:right;line-height:2.3rem;height:1.5rem;">库存: {{stockCount}} {{goodsunit}}</span>
						</p>
						<p v-if="estimate" style="min-width: 1rem;text-align:left;color:#0C0D0C;font-size: .6rem;padding:0 .75rem;">
							<span style="display:inline-block;background: #EEF8E7;">
          <span style="color:#4B403E;" v-if="goodsType == 6">
            每{{goodsunit}}{{wsprice}}元
          </span> {{estimate}}
							</span>
						</p>
						<ThreeKnights :prodarea='prodarea' :storageConditions='storageConditions' :brandname='brandname'></ThreeKnights>
						<div class="grayBar" v-if="deliveryTime"></div>
						<ArrivingTime v-if="deliveryTime" :deliveryTime='deliveryTime' :startBookTm='startBookTm' :endBookTm='endBookTm' :distributionprocessingtime='distributionprocessingtime'></ArrivingTime>
						<div class="grayBar"></div>
						<div class="image_text">
							<h4 style="text-align:center;padding:0;height:1.8rem;width: 95%;margin-left:2.5%;">
          <p
            style="color:#4B4B4B;height:100%;padding:0;width:3.8rem;margin:0 auto;line-height:1.6rem;border-bottom:3px solid #52BD13;font-size:.8rem;">
            商品详情
          </p>
        </h4>
							<div v-for="(item,index) in imgurl" class="image_text_con" :key="index">
								<img v-bind:src="item || 'static/image/demo2.png'" />
							</div>
						</div>
					</div>
				</VerticalScroll>
			</div>
		</div>
		<div class="purchased" style="width:100%;height:3rem;position: relative;bottom: 0">
			<div class="edit_data" v-if="stockCount > 0 && commodityInfor">
				<span>购买数量：</span>
				<i class="del_cart" style="float: left" @click="delnumi"></i>
				<input type="num" v-model="goodsnum" readonly/>
				<i class="add_to_cart" @click="addnumi"></i>
			</div>
			<div @click="showCartModle" v-if="stockCount > 0 && commodityInfor" class="aui-btn aui-btn-danger aui-btn-sm add_to_cart" style="width: 6rem;height: 100%;bottom: 0;position:absolute;z-index: 1;right: 0;line-height: 3rem;font-size: 0.7rem;width:6rem;border-radius: 0">
				立即兑换
			</div>
			<div v-if="stockCount <= 0" class="aui-btn aui-btn-danger aui-btn-sm add_to_cart" style="width: 6rem;height: 100%;bottom: 0;position:absolute;z-index: 1;right: 0;line-height: 3rem;font-size: 0.7rem;width:6rem;border-radius: 0">
				已售罄
			</div>
		</div>
		<!--回到顶部  -->
		<button-to-top @goTop="goTop" bottom='5rem' style="z-index:10"></button-to-top>
	</div>
</template>
<script>
	import Header from "../header";
	import axios from "axios";
	import { Toast } from '../../utils/toast.js';
	/*import { translateDetailData, getLastStockCountNum } from '@/utils/TranslateDetailDate';*/
	import Carousel from "../../real-components/HomeCarousel";
	import { mapState, mapGetters, mapMutations } from 'vuex';
	import DetailProce from '../../real-components/DetailProce';
	import CartMode from '../../real-components/CartMode';
	import CommodityRecommendList from '@/real-components/CommodityRecommendList';
	import CartModle from '@/real-components/CartMode';
	import ThreeKnights from './ThreeKnights';
	import ArrivingTime from './ArrivingTime';
	import VerticalScroll from "../../real-components/VerticalScroll";
	import ButtonToTop from "../../real-components/ButtonToTopForTest";
	import { showLoading, hideLoading } from "../../utils/loading";
	export default {
		props: {},
		data() {
			return {
				midPartHeight: '100%',
				id: '',
				goodsId: 0,
				goodsName: "",
				goodsspec: "",
				wsprice: "",
				normalprice: "",
				prodarea: "",
				brandname: "",
				imgurl: "",
				transferUrl: [],
				number: 0,
				commodityInfor: null,
				goodsUnit: '',
				minsaleqty: '',
				stockCount: '', //库存
				processlist: [],
				secTitle: '',
				goodsunit: '',
				storageConditions: '', //储存条件
				distributionprocessingtime: '',
				workingInfo: {
					"processingattribute": '',
					"procemoney": 0,
					"processcomments": ''
				},
				deliveryTime: "",
				activeNameList: [],
				activeStartTime: [],
				activeEndTime: [],
				startBookTm: "",
				endBookTm: "",
				goodsCode: "",
				goodsClassId: "",
				classCode: "",
				normalDisplay: false,
				traceabilityaddress: '',
				estimate: null,
				perPrice: null,
				goodsType: '',
				//商品购买数量
				goodsnum: 1,
				buyLimit: '',
				requiredIntegral: 0,
				rid: '',
				myPointsdata: '',
				exchangeQuantity: null,
			}
		},
		components: {
			"v-header": Header,
			"v-carousel": Carousel,
			DetailProce,
			CartMode,
			CommodityRecommendList,
			CartModle,
			ThreeKnights,
			ArrivingTime,
			VerticalScroll,
			ButtonToTop
		},
		computed: {
			...mapGetters({
				userInfo: 'xhModules/userInfo',
				sessionId: 'xhModules/sessionId',
			}),
			/*lastStockCountNum() {
				var detail = this.commodityInfor
				if(detail) {
					detail = translateDetailData(detail)
					return detail.lastStockCountNum
				}
				return 1
			},*/
			mGoodsId: {
				set: function(val) {
					this.id = val;
				},
				get: function() {
					return this.id;
				}
			},
			//获取屏幕宽度
			screenWidth() {
				if(window.environment === "production") {
					return window.innerWidth;
				} else {
					return 375;
				}
			},
		},
		mounted() {
			this.setOrdergoback(0)
			this.setaderssgorder(0)
			this.queryMyPoints() //获取用户的积分
			this.getDetail(); //获取详情信息
		},
		updated() {
			this.$nextTick(() => {
				var midPart = this.$refs.midPart
				if(midPart) {
					this.midPartHeight = midPart.offsetHeight + 'px'
				}
			})
		},
		methods: {
			...mapMutations('xxy', [
				"setconfigtokenNew",
				'setdetailgoback',
				'setOrdergoback',
				'setaderssgorder'
			]),
			//获取用户的积分信息
			queryMyPoints() {
				let config = {
					url: window.api.customer_host + '/customer/getCustomer',
					method: 'GET',
					headers: {
						'sessionId': localStorage.getItem('sessionId'),
					},
				};
				axios(config).then((res) => {
					this.myPointsdata = res.data.data[0]
				})
			},
			//跳转到积分商城
			goBack() {
				this.setdetailgoback(2);
				window.history.go(-1);
			},
			//购物车减号
			delnumi() {
				this.goodsnum--
					if(this.goodsnum == 0) {
						this.goodsnum = 1
					}
			},
			//购物车加号
			addnumi() {
				if(this.exchangeQuantity && this.exchangeQuantity > 0 && this.goodsnum == (this.buyLimit - this.exchangeQuantity)) {
					Toast({
						message: '已达该商品购买上线',
						duration: 1000,
						type: "fail"
					})
					return
				} else if(this.goodsnum == this.buyLimit) {
					this.goodsnum = this.buyLimit
					Toast({
						message: '已达该商品购买上线',
						duration: 1000,
						type: "fail"
					})
					return
				}
				this.goodsnum++
			},
			goTop() {
				this.$refs.verticalScroll && this.$refs.verticalScroll.goTop()
			},
			//跳转到溯源页面
			goSource() {
				this.traceabilityaddress && this.$router.push({
					'path': "originSource",
					'query': {
						urlData: this.traceabilityaddress
					}
				});
			},
			showCartModle() {
				//立即兑换
				this.setconfigtokenNew(1)
				if(this.myPointsdata.remainingscore < this.goodsnum * this.requiredIntegral) {
					Toast({
						message: '积分不足兑换该商品',
						duration: 2000,
						type: "fail"
					})
				} else {
					this.$router.push({
						path: 'ConfirmOrderIntegral',
						query: {
							"goodsData": JSON.stringify(this.commodityInfor),
							"goodsnum": this.goodsnum,
							"rid": JSON.stringify(this.$route.query.rid),
							'integralprice':JSON.stringify(this.requiredIntegral)
							/*JSON.stringify(this.rid)*/
						}
					});
				}

			},
			/*translateDetailData,*/
			//获取商品详情
			async getDetail() {
				/*let detailsInfo = await localforage.getItem(goodsId.toString());
				detailsInfo && this.showDetailInfo(detailsInfo);*/
				var rids = []
				rids.push(this.$route.query.rid)
				let options = {
					method: "post",
					url: window.api.trade_host + '/integralGoods/getIntegralGoodsByRids',
					data: {
						/*goodsCode: this.$route.query.goodsCode,*/
						rids: rids,
						goodsType: 2,
						storeCode: localStorage.getItem('storeCode'),
					},
					headers: {
						sessionId: localStorage.getItem("sessionId"),
					}
				}

				axios(options).then(res => {
					let DetailData = null
					if(res.data.data[0]) {
						DetailData = JSON.parse(res.data.data[0][0].queryMallGoodsVO);
						this.buyLimit = res.data.data[0][0].buyLimit
						this.requiredIntegral = res.data.data[0][0].requiredIntegral
						this.exchangeQuantity = res.data.data[0][0].exchangeQuantity
						this.rid = res.data.data[0][0].rid
						this.goodsId = res.data.data[0][0].goodsCode
						this.goodsCode = res.data.data[0][0].goodsCode
					}
					if(DetailData) {
						this.showDetailInfo(DetailData, this.goodsId);
					} else {
						Toast({
							message: '该商品已经下架',
							duration: 2000,
							type: "fail"
						})
						setTimeout(() => {
							window.history.go(-1);
						}, 1000)
					}
				}).catch(res => {

				});
			},
			async showDetailInfo(data, goodsId) {
				/*if(goodsId) {
					let previousData = await localforage.getItem(goodsId.toString());
					localforage.setItem(goodsId.toString(), data);
					if(JSON.stringify(data) === JSON.stringify(previousData)) {
						return false;
					};
				}*/
				var conditions = this.$refs.conditions;
				var urlList = data.urllist;
				this.commodityInfor = data;
				this.goodsName = data.goodsname;
				this.classCode = data.classcode;
				this.goodsClassId = data.goodsclassid;
				this.goodsspec = data.goodsspec;
				this.distributionprocessingtime = data.distributionprocessingtime;
				if(data.goodstype == 7) {
					this.goodsType = 7;
					if(data.goodsunit == 'g' || data.goodsunit == 'G') {
						this.goodsunit = 'g';
						this.minsaleqty = 500;
						this.normalprice = parseFloat(data.normalprice * 0.5 || 0).toFixed(2)
						this.wsprice = parseFloat(data.wsprice * 0.5 || 0).toFixed(2)
					}
					if(data.goodsunit == 'kg' || data.goodsunit == 'KG' || data.goodsunit == 'Kg' || data.goodsunit == 'kG') {
						this.goodsunit = 'kg';
						this.minsaleqty = 500;
						this.wsprice = parseFloat(data.wsprice * 0.5 || 0).toFixed(2);
						this.normalprice = parseFloat(data.normalprice * 0.5 || 0).toFixed(2);
					}
					this.stockCount = data.stockcount ? parseFloat(data.stockcount).toFixed(2) : '0.00';
				} else if(data.goodstype == 6) {
					this.goodsType = 6;
					this.estimate = `约${data.weighingsmall}~${data.weighingbig}kg/${data.mallUnit || ''}`;
					this.goodsunit = data.mallUnit || '';
					this.stockCount = data.stockcount ? Math.floor(data.stockcount / data.weighingbig) : 0;
					this.wsprice = parseFloat(data.wsprice * data.weighingbig || 0).toFixed(2)
					this.perPrice = parseFloat(data.wsprice * 0.5).toFixed(2)
					this.normalprice = parseFloat(data.normalprice * 0.5 || 0).toFixed(2);
				} else {
					this.goodsunit = data.goodsunit;
					this.wsprice = parseFloat(data.wsprice || 0).toFixed(2)
					this.normalprice = parseFloat(data.normalprice * 0.5 || 0).toFixed(2);
					this.stockCount = data.stockcount ? data.stockcount : 0;
				}
				this.mGoodsId = data.goodscode;
				this.prodarea = data.prodarea;
				this.brandname = data.brandname;
				this.goodsUnit = data.goodsunit || '件';
				this.secTitle = data.subtitle; // 特色描述
				this.traceabilityaddress = data.traceabilityaddress; //溯源链接
				// 储存条件
				if(data.storageconditions == 0) {
					this.storageConditions = "常温"
				} else if(data.storageconditions == 1) {
					this.storageConditions = "冷冻"
				} else if(data.storageconditions == 2) {
					this.storageConditions = "冷藏"
				} else if(data.storageconditions == 3) {
					this.storageConditions = "热链"
				} else {
					this.storageConditions = "常温"
				}
				let flag = false;
				if(urlList && urlList.length) {
					urlList.forEach(function(element) {
						element.Imgurltype == 2 && element.imgurl ? this.imgurl = element.imgurl.split(" ") : "";
						if(element.Imgurltype == 0) {
							flag = true;
							let Arr = new Array();
							let arr = element.imgurl.split(" ");
							for(let item of arr) {
								let Obj = new Object();
								Obj.publicityPicture = item;
								Arr.push(Obj);
							}
							this.transferUrl = Arr;
						}
					}, this);
				}
				if(!flag) {
					let Arr = new Array();
					let Obj = new Object();
					Obj.publicityPicture = {
						"publicityPicture": "static/image/demo2.png"
					};
					Arr.push(Obj);
					this.transferUrl = Arr;
				}
				if(localStorage.getItem("sessionId")) {
					this.getDeliveryTime(data);
				}
				hideLoading();
			},
			//获取预计到达时间
			getDeliveryTime(data) {
				let options = {
					method: "get",
					url: api.trade_host + "/delivery_config/first/tm_interval",
					params: {
						deliveryType: data.distributiontype,
						machineTm: data.distributionprocessingtime,
						readyTm: data.distributionpreparationtime,
						storeCode: localStorage.getItem("storeCode")
					},
					headers: {
						sessionId: localStorage.getItem("sessionId")
					}
				}
				axios(options).then(data => {
					if(data.data.data[0]) {
						this.deliveryTime = data.data.data[0].deliveryDate;
						this.startBookTm = data.data.data[0].delivery.startBookTm;
						this.endBookTm = data.data.data[0].delivery.endBookTm;
					}
				})
			}
		},
		created() {

		}
	}
</script>
<style scoped>
	.interpret span {
		height: 100%;
		line-height: 100%;
	}
	
	#shade {
		width: 100%;
		height: 100%;
		background: lightgray;
		position: absolute;
		top: 0;
		left: 0;
		opacity: .5;
		z-index: 10;
		display: none;
	}
	
	body {
		width: 100%;
	}
	
	.grayBar {
		width: 100%;
		height: 15px;
		background: #F5F5F5;
	}
	
	.price {
		background: white;
		text-align: left;
	}
	
	.aui-ellipsis-1 {
		overflow: hidden;
		white-space: nowrap;
		text-overflow: ellipsis;
	}
	
	.goodsName {
		font-size: 1rem;
		padding: 0.2rem 0.75rem;
		overflow: hidden;
		text-overflow: ellipsis;
		word-wrap: break-word;
		word-break: break-all;
		white-space: normal !important;
		-webkit-line-clamp: 2;
		-webkit-box-orient: vertical;
	}
	
	.goods_detail {
		margin-bottom: 0;
		text-align: center;
		position: relative;
		-webkit-overflow-scrolling: touch;
	}
	
	.goods_detail p {
		padding: 0.2rem 0.75rem;
	}
	
	.second_title {
		width: 100%;
		font-size: 0.8rem;
		overflow: hidden;
		white-space: pre-wrap;
		word-break: break-all;
	}
	
	p {
		font-size: 0.7rem;
		color: #9a9a9a;
	}
	
	.njfont {
		font-family: "njfont" !important;
		font-style: normal;
		font-size: 1rem;
		line-height: 1;
	}
	
	.labels {
		margin-bottom: 0.7rem;
	}
	
	.right_line {
		border-right: 1px solid #EAEAEA;
		height: 1.6rem;
		position: absolute;
		top: 1.2rem;
		right: 0;
	}
	
	.purchased .edit_data {
		position: relative;
		bottom: 0;
		right: 0;
	}
	
	.purchased {
		height: 3rem;
		background: rgba(255, 255, 255, 0.9);
		overflow: hidden;
		position: relative;
		width: 100%;
		left: 0;
		bottom: 0;
		display: block;
		border-top: 1px solid #eaeaea;
		z-index: 99;
	}
	
	.purchased .server_icon {
		float: left;
	}
	
	.content {
		width: 100%;
		height: 100%;
		display: flex;
		flex-direction: column;
		align-items: center;
		justify-content: space-between;
	}
	
	.midPart {
		flex: 1;
		height: 100%;
		width: 100%;
		overflow: hidden
	}
	
	.shopping_cart {
		position: absolute;
		top: 0;
		left: 0.5rem;
		bottom: 0;
		margin: auto;
		font-size: 1.2rem;
		color: #7c7c7c;
	}
	
	.coupon {
		font-size: 12px;
		background: #00B762;
		padding: 2px;
		border-radius: .2rem;
		color: white;
	}
	
	#Coupons {
		width: 100%;
	}
	
	#Coupons>ul {
		width: 100%;
	}
	
	#Coupons>ul>li {
		width: 100%;
		padding-left: .7rem;
	}
	/* .explain{ */
	/* position: absolute;
    left:50%;
    top:50%;
    transform: translate(-50%,-50%); */
	/* } */
	/*add by lanxin 2018-01-06*/
	
	.image_text_con {
		padding: 0;
	}
	/*.add_to_cart:last-child::after{
		top: 1.5rem;
	}*/
	
	.intgoodsnumdiv {
		display: inline-block;
		color: #EF5423;
		font-size: 1rem;
		margin-left: 1rem;
	}
</style>